package cn.main.core;

import cn.main.entity.sys.Role;
import cn.main.entity.sys.SysColumn;
import cn.main.entity.sys.SysFunction;

import java.util.Set;

/**
 * Author: chengwei
 * Date:   2016/7/13
 * Time:   15:56
 */
public class AuthorityHelper {

    //判断用户有无栏目访问权限
    public static boolean hasColumnAuthority(UserSession session, SysColumn column) {
        if (session == null || column == null) return false;
        Set<Role> roles = session.getRoles();
        Set<SysFunction> functions = column.getFunctions();
        if (functions == null) {
            return false;
        }
        if (roles == null) return false;
        for (SysFunction function : functions) {
            if (hasFunctionAuthority(session, function)) {
                return true;
            }
        }
        return false;
    }
    
    public static boolean hasFunctionAuthority(UserSession session, SysFunction function) {
        if (session == null || function == null) return false;
        if (function.isaPublic()) return true;
        Set<Role> roles = session.getRoles();
        if (roles == null || roles.size() == 0) return false;
        for (Role role : roles) {
            if (hasFunctionAuthority(role,function)) {
                return true;
            }
        }
        return false;
    }
    
    //判断角色有无构架权限
    private static boolean hasFunctionAuthority(Role role, SysFunction function) {
        if (role == null || function == null) {
            return false;
        }
        Set<SysFunction> functions = role.getFunctions();
        if (functions == null) {
            return false;
        }
        for (SysFunction f : functions) {
            if (function.equals(f)) {
                return true;
            }
        }

        Set<Role> roles = role.getRoles();
        if (roles == null || roles.size() == 0) return false;
        for (Role r : roles) {
            if (hasFunctionAuthority(r,function)) {
                return true;
            }
        }
        return false;
    }

    //判断角色有无栏目权限
    private static boolean hasColumnAuthority(Role role,SysColumn column) {
        if (role == null || column == null) {
            return false;
        }
        Set<SysFunction> functions = role.getFunctions();
        if (functions == null) {
            return false;
        }
        for (SysFunction function : functions) {
            if (function.isaPublic() || function.getColumn().equals(column)) {
                return true;
            }
        }

        Set<Role> roles = role.getRoles();
        if (roles == null || roles.size() == 0) return false;
        for (Role r : roles) {
            if (hasColumnAuthority(r,column)) {
                return true;
            }
        }
        return false;
    }
}
